package textapp.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import textapp.dao.model.AppConfig;

public class AppConfigDao {
	
	public AppConfig findByName(String paramName) {
		EntityManager em = EMUtil.createEntityManager();
		Query q = em.createNamedQuery("AppConfig.getByParamName");
		q.setParameter("param", paramName);
		List<AppConfig> result = q.getResultList();
		if (result.size() > 0) {
			return result.get(0);
		}else {
			return null;
		}
	}
	
	public AppConfig saveOrUpdate(AppConfig config) {
		AppConfig cfg = findByName(config.getParam());
		if (cfg != null) {
			EntityManager em = EMUtil.createEntityManager();
			em.getTransaction().begin();
			AppConfig c = em.find(AppConfig.class, cfg.getId());
			c.setValue(config.getValue());
			em.getTransaction().commit();
			em.close();
			return c;
		} else {
			config.setId(0);
			EntityManager em = EMUtil.createEntityManager();
			em.getTransaction().begin();
			em.persist(config);
			em.getTransaction().commit();
			em.close();
			return config;
		}
	}
	
}
